package com.cby.android.base.localsocket

import android.net.LocalServerSocket
import android.net.LocalSocket
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.cby.android.base.R
import com.cby.android.base.kotlin.start
import java.io.PrintWriter


/**
 * @description: server在主进程
 * @author: ChenBaoYang
 * @createDate: 2022/3/24 10:57 上午
 */
class MyLocalSocketServerActivity : AppCompatActivity() {


    private var serverThread: MyServerThread? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_local_socket_server)

    }

    fun startServer(view: View) {
        if(serverThread == null) {
            serverThread = MyServerThread()
        }
        serverThread?.start()

    }

    fun stopServer() {
        serverThread?.exit()
    }

    override fun onDestroy() {
        stopServer()
        super.onDestroy()
    }

    fun openClientPage(view: View) {
        start(MyLocalSocketClientActivity::class.java)
    }
}

class MyServerThread : Thread() {

    private val tag = "chenby"

    val addressServer = "com.cby.server.local.socket"

    var exit: Boolean = false

    override fun run() {
        var serverSocket: LocalServerSocket? = null
        try {
            // 创建LocalServerSocket
            serverSocket = LocalServerSocket(addressServer)
            while (!exit) {
                val localSocket = serverSocket.accept()
                val credentials = localSocket.peerCredentials
                Log.i(tag,"accept socket uid:$credentials.getUid()")
                MyConnectThread(localSocket).start()
            }
        }catch (e: Exception) {
            Log.i(tag, "server e = "+e.message)
        }finally {
            serverSocket?.close()
        }
    }

    fun exit() {
        exit = true
        try {
            interrupt()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }


}

class MyConnectThread(private val localSocket: LocalSocket) : Thread() {

    private val tag = "chenby"

    override fun run() {

        // 写出数据
        val cmd: ByteArray = "服务端数据传递给客户端".toByteArray()
        val len2 = cmd.size
        val out = localSocket.outputStream
        out.write(cmd, 0, len2)
        Log.d(tag, "Server write: 服务端数据传递给客户端")

        // 读取数据
        val input = localSocket.inputStream
        val buffer = ByteArray(1024)
        val len = input.read(buffer)
        Log.d(tag, "Server read:" + String(buffer, 0, len))

        /*val writer = PrintWriter(localSocket.outputStream)
        writer.println("this is server\u0000")
        writer.flush()
        writer.close()*/

    }
}